<?php
require_once __DIR__ . '/../functions.php';

// 检查管理员权限
if (!isAdmin()) {
    redirect('../index.php', '您没有权限访问此页面', 'danger');
}

$db = getDB();

// 处理表单提交
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $action = $_POST['action'] ?? '';
    
    if ($action == 'add_option') {
        // 添加配置选项
        $configType = $_POST['config_type'] ?? '';
        $optionValue = $_POST['option_value'] ?? '';
        $optionLabel = $_POST['option_label'] ?? '';
        $sortOrder = intval($_POST['sort_order'] ?? 0);
        
        if (empty($configType) || empty($optionValue) || empty($optionLabel)) {
            $error = '请填写完整的配置信息';
        } else {
            // 检查是否已存在
            $stmt = $db->prepare("SELECT id FROM config_options WHERE config_type = ? AND option_value = ?");
            $stmt->execute([$configType, $optionValue]);
            
            if ($stmt->fetch()) {
                $error = '该选项值已存在';
            } else {
                $stmt = $db->prepare("INSERT INTO config_options (config_type, option_value, option_label, sort_order) VALUES (?, ?, ?, ?)");
                if ($stmt->execute([$configType, $optionValue, $optionLabel, $sortOrder])) {
                    $success = '配置选项添加成功';
                } else {
                    $error = '配置选项添加失败';
                }
            }
        }
    } elseif ($action == 'update_option') {
        // 更新配置选项
        $id = intval($_POST['id'] ?? 0);
        $optionLabel = $_POST['option_label'] ?? '';
        $sortOrder = intval($_POST['sort_order'] ?? 0);
        $isActive = isset($_POST['is_active']) ? 1 : 0;
        
        if ($id <= 0 || empty($optionLabel)) {
            $error = '请填写完整的信息';
        } else {
            $stmt = $db->prepare("UPDATE config_options SET option_label = ?, sort_order = ?, is_active = ? WHERE id = ?");
            if ($stmt->execute([$optionLabel, $sortOrder, $isActive, $id])) {
                $success = '配置选项更新成功';
            } else {
                $error = '配置选项更新失败';
            }
        }
    } elseif ($action == 'delete_option') {
        // 删除配置选项
        $id = intval($_POST['id'] ?? 0);
        
        if ($id <= 0) {
            $error = '选项ID无效';
        } else {
            $stmt = $db->prepare("DELETE FROM config_options WHERE id = ?");
            if ($stmt->execute([$id])) {
                $success = '配置选项删除成功';
            } else {
                $error = '配置选项删除失败';
            }
        }
    }
}

// 获取所有配置选项
$configTypes = [
    'delivery_location' => '收货地',
    'order_platform' => '下单平台',
    'group_name' => '群组名称'
];

$options = [];
foreach ($configTypes as $type => $label) {
    $stmt = $db->prepare("SELECT * FROM config_options WHERE config_type = ? ORDER BY sort_order ASC, option_label ASC");
    $stmt->execute([$type]);
    $options[$type] = $stmt->fetchAll();
}

include __DIR__ . '/header.php';
?>

<div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
    <h1 class="h2">配置选项管理</h1>
    <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#addOptionModal">
        <i class="bi bi-plus-circle"></i> 添加选项
    </button>
</div>

<?php if (isset($error)): ?>
    <div class="alert alert-danger alert-dismissible fade show" role="alert">
        <i class="bi bi-exclamation-triangle-fill"></i> <?php echo htmlspecialchars($error); ?>
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    </div>
<?php endif; ?>

<?php if (isset($success)): ?>
    <div class="alert alert-success alert-dismissible fade show" role="alert">
        <i class="bi bi-check-circle-fill"></i> <?php echo htmlspecialchars($success); ?>
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    </div>
<?php endif; ?>

<!-- 配置选项列表 -->
<?php foreach ($configTypes as $type => $label): ?>
    <div class="card mb-4">
        <div class="card-header bg-primary text-white">
            <h5 class="mb-0">
                <i class="bi bi-list"></i> <?php echo $label; ?>
                <span class="badge bg-light text-primary ms-2"><?php echo count($options[$type]); ?></span>
            </h5>
        </div>
        <div class="card-body">
            <?php if (empty($options[$type])): ?>
                <div class="text-center text-muted py-3">
                    <i class="bi bi-inbox display-4"></i>
                    <p class="mt-2 mb-0">暂无<?php echo $label; ?>选项</p>
                    <button type="button" class="btn btn-primary mt-3" onclick="setConfigType('<?php echo $type; ?>')">
                        <i class="bi bi-plus-circle"></i> 添加<?php echo $label; ?>选项
                    </button>
                </div>
            <?php else: ?>
                <div class="table-responsive">
                    <table class="table table-hover">
                        <thead>
                            <tr>
                                <th>ID</th>
                                <th>选项值</th>
                                <th>显示名称</th>
                                <th>排序</th>
                                <th>状态</th>
                                <th>创建时间</th>
                                <th>操作</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($options[$type] as $option): ?>
                                <tr>
                                    <td><?php echo $option['id']; ?></td>
                                    <td>
                                        <code><?php echo htmlspecialchars($option['option_value']); ?></code>
                                    </td>
                                    <td><?php echo htmlspecialchars($option['option_label']); ?></td>
                                    <td><?php echo $option['sort_order']; ?></td>
                                    <td>
                                        <span class="badge bg-<?php echo $option['is_active'] ? 'success' : 'secondary'; ?>">
                                            <?php echo $option['is_active'] ? '启用' : '禁用'; ?>
                                        </span>
                                    </td>
                                    <td><?php echo date('Y-m-d H:i', strtotime($option['created_at'])); ?></td>
                                    <td>
                                        <div class="btn-group" role="group">
                                            <button type="button" class="btn btn-sm btn-outline-primary" 
                                                    onclick="editOption(<?php echo $option['id']; ?>, '<?php echo addslashes($option['option_label']); ?>', <?php echo $option['sort_order']; ?>, <?php echo $option['is_active']; ?>)"
                                                    data-bs-toggle="tooltip" title="编辑">
                                                <i class="bi bi-pencil"></i>
                                            </button>
                                            <form method="POST" style="display: inline;" 
                                                  onsubmit="return confirm('确定要删除这个选项吗？');">
                                                <input type="hidden" name="action" value="delete_option">
                                                <input type="hidden" name="id" value="<?php echo $option['id']; ?>">
                                                <button type="submit" class="btn btn-sm btn-outline-danger" 
                                                        data-bs-toggle="tooltip" title="删除">
                                                    <i class="bi bi-trash"></i>
                                                </button>
                                            </form>
                                        </div>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            <?php endif; ?>
        </div>
    </div>
<?php endforeach; ?>

<!-- 添加选项模态框 -->
<div class="modal fade" id="addOptionModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">添加配置选项</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <form method="POST" id="addOptionForm">
                    <input type="hidden" name="action" value="add_option">
                    
                    <div class="mb-3">
                        <label for="config_type" class="form-label">配置类型 <span class="text-danger">*</span></label>
                        <select class="form-select" id="config_type" name="config_type" required>
                            <option value="">请选择配置类型</option>
                            <?php foreach ($configTypes as $type => $label): ?>
                                <option value="<?php echo $type; ?>"><?php echo $label; ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    
                    <div class="mb-3">
                        <label for="option_value" class="form-label">选项值 <span class="text-danger">*</span></label>
                        <input type="text" class="form-control" id="option_value" name="option_value" 
                               placeholder="请输入选项值（英文，无空格）" required>
                        <div class="form-text">选项值用于程序内部识别，建议使用英文和下划线</div>
                    </div>
                    
                    <div class="mb-3">
                        <label for="option_label" class="form-label">显示名称 <span class="text-danger">*</span></label>
                        <input type="text" class="form-control" id="option_label" name="option_label" 
                               placeholder="请输入显示名称" required>
                        <div class="form-text">显示名称用于界面展示，支持中文</div>
                    </div>
                    
                    <div class="mb-3">
                        <label for="sort_order" class="form-label">排序</label>
                        <input type="number" class="form-control" id="sort_order" name="sort_order" 
                               value="0" min="0">
                        <div class="form-text">数字越大越靠前</div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" onclick="submitAddForm()">
                    <i class="bi bi-plus-circle"></i> 添加选项
                </button>
            </div>
        </div>
    </div>
</div>

<!-- 编辑选项模态框 -->
<div class="modal fade" id="editOptionModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">编辑配置选项</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <form method="POST" id="editOptionForm">
                    <input type="hidden" name="action" value="update_option">
                    <input type="hidden" name="id" id="edit_id">
                    
                    <div class="mb-3">
                        <label for="edit_option_label" class="form-label">显示名称 <span class="text-danger">*</span></label>
                        <input type="text" class="form-control" id="edit_option_label" name="option_label" required>
                    </div>
                    
                    <div class="mb-3">
                        <label for="edit_sort_order" class="form-label">排序</label>
                        <input type="number" class="form-control" id="edit_sort_order" name="sort_order" min="0">
                    </div>
                    
                    <div class="mb-3">
                        <div class="form-check form-switch">
                            <input class="form-check-input" type="checkbox" id="edit_is_active" name="is_active" value="1">
                            <label class="form-check-label" for="edit_is_active">
                                启用该选项
                            </label>
                        </div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" onclick="submitEditForm()">
                    <i class="bi bi-save"></i> 保存修改
                </button>
            </div>
        </div>
    </div>
</div>

<script>
function setConfigType(type) {
    document.getElementById('config_type').value = type;
    const modal = new bootstrap.Modal(document.getElementById('addOptionModal'));
    modal.show();
}

function submitAddForm() {
    const form = document.getElementById('addOptionForm');
    if (form.checkValidity()) {
        form.submit();
    } else {
        form.classList.add('was-validated');
    }
}

function editOption(id, label, sortOrder, isActive) {
    document.getElementById('edit_id').value = id;
    document.getElementById('edit_option_label').value = label;
    document.getElementById('edit_sort_order').value = sortOrder;
    document.getElementById('edit_is_active').checked = isActive;
    
    const modal = new bootstrap.Modal(document.getElementById('editOptionModal'));
    modal.show();
}

function submitEditForm() {
    const form = document.getElementById('editOptionForm');
    if (form.checkValidity()) {
        form.submit();
    } else {
        form.classList.add('was-validated');
    }
}

// 初始化工具提示
var tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'));
var tooltipList = tooltipTriggerList.map(function (tooltipTriggerEl) {
    return new bootstrap.Tooltip(tooltipTriggerEl);
});
</script>

<?php include __DIR__ . '/footer.php'; ?>